<template>
  <d2-container>
    <el-main>
      <h3>进货/出货</h3>
      <el-radio-group v-model="type" :disabled="disabled">
<!--        <el-radio :label="0">进库</el-radio>-->
        <el-radio :label="1">出库</el-radio>
      </el-radio-group>
      <el-row>
        <el-col :span="6">
          <h3>所在校区：</h3>
          <el-select
            v-model="school"
            filterable
            placeholder="可输入名称搜索"
            @change="schoolSelected"
            :disabled="disabled"
          >
            <el-option
              v-for="item in schoolList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <h3>领取人：</h3>
          <el-select v-model="staff" filterable multiple placeholder="可输入姓名搜索" :disabled="disabled">
            <el-option
              v-for="item in staffList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <h3>采购列表：</h3>
      <el-button
        @click="selectProduct = true"
        style="float:left;margin:10px"
        icon="el-icon-plus"
        size="small"
        type="primary"
         :disabled="disabled"
      >添加采购的商品</el-button>
      <el-dialog title="商品列表" :visible.sync="selectProduct">
        <el-input placeholder="请输入商品名称" v-model="searchName" size="small">
          <el-button slot="append" icon="el-icon-search" @click="searchProduct"></el-button>
        </el-input>
        <el-table :data="productList">
          <el-table-column property="name" label="商品名称"></el-table-column>
          <el-table-column prop="wholeSalePrice" label="单价"></el-table-column>
          <el-table-column prop="storage" label="库存"></el-table-column>
          <el-table-column label="数量">
          <template slot-scope="scope">
              <input v-model="scope.row.count" style="width:50px" type="number" min="0"></input>
          </template>
          </el-table-column>
        <el-table-column  label="操作">
          <template slot-scope="scope">
            <el-button @click="addProduct(scope.row)" type="text">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
        <el-pagination small layout="prev, pager, next" :total="searchCount" @current-change="currentChange"></el-pagination>
      </el-dialog>
      <el-table :data="selectedProductList" border style="width: 100%">
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <!-- <el-table-column prop="productCategory[0].name" label="商品种类"></el-table-column> -->
        <el-table-column prop="wholeSalePrice" label="单价"></el-table-column>
        <el-table-column label="数量" >
          <template slot-scope="scope">
              <input v-model="selectedProductList[scope.$index].count" style="width:50px" type="number" min="0" @change="sum" :disabled="disabled"></input>
          </template>
        </el-table-column>
        <el-table-column  label="操作">
          <template slot-scope="scope">
            <el-button @click="deleteClick(scope.$index)" type="text" size="small" :disabled="disabled">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <h3>数量总和：{{total}}</h3>
      <h3>金额合计：{{price}}</h3>
    </el-main>
    <el-footer>
      <el-button type="primary" @click="submit">提交</el-button>
      <!-- <el-button @click="edit" v-show="editShow">修改</el-button> -->
    </el-footer>
  </d2-container>
</template>

<script>
// import { request } from "http";
import request from "@/plugin/axios";
import { constants } from "crypto";
    import {mapState} from "vuex";

export default {
  data() {
    return {
      editShow: false,
      disabled: false,
      id: undefined,
      school: undefined,
      schoolList: [],
      staff: undefined,
      staffList: [],
      selectProduct:false,
      searchName: undefined,
      searchCount: undefined,
      productList: [],
      selectedProductList: [],
      total:0,
      price:0,
      type:undefined
    };
  },
  computed: {
            ...mapState('d2admin/user', ['info']),
        },
  methods: {
    filterMethod(query, item) {
      return item.name.indexOf(query) != -1;
    },
    getSchoolList(pageSize) {
      this.staffList = [];
      let data = {};
      data.pageSize = pageSize;
      request({
        url: "/school/getSchoolList",
        method: "post",
        data
      }).then(res => {
        this.schoolList = res.data.school;
        // 返回数据
      });
    },
    schoolSelected() {
      this.getStaffList(-1);
    },
    getStaffList(pageSize) {
      let data = {};
      data.pageSize = pageSize;
      data.school = this.school;
      request({
        url: "/staff/getStaffList",
        method: "post",
        data
      }).then(res => {
        this.staffList = res.data.staff;
        // 返回数据
      });
    },
    searchProduct() {
      this.getProductList(1);
    },
    currentChange(e){
      this.getProductList(e);
    },
    getProductList(page) {
      request({
        url: "/product/getProductList",
        method: "post",
        data: { page: page, pageSize: 10, name: this.searchName }
      }).then(res => {
          res.data.product.forEach(e => {
              e.count = undefined
          });
        (this.productList = res.data.product),
          (this.searchCount = res.data.count);
      });
    },
    addProduct(e){
        if(this.selectedProductList.map(event =>{return event._id}).indexOf(e._id) == -1){
        this.selectedProductList.push(e)
        }else{
        this.$message({
          showClose: true,
          message: '已经添加这个商品了哦',
          type: 'error'
        });
        }
        this.sum()
    },
    deleteClick(e){
        this.selectedProductList.splice(e,1)
        this.sum()
    },
    sum(){
        let total = 0;
        let price =0
        for(var i=0;i<this.selectedProductList.length;i++){
            total += parseInt(this.selectedProductList[i].count)
            price += parseInt(this.selectedProductList[i].wholeSalePrice*this.selectedProductList[i].count)
        }
        this.total = total
        this.price = price
    },
    submit(){
        let data = {}
        data.type = this.type
        data.school = this.school
        data.staff = this.staff
        data.products = []
        for(let i=0;i<this.selectedProductList.length;i++){
            let tempproduct = {}
            tempproduct.product = this.selectedProductList[i]._id
            tempproduct.number = this.selectedProductList[i].count
            data.products.push(tempproduct)
        }
      request({
        url: "/productOrder/newWarehouse",
        method: "post",
        data: data
      }).then(res => {
        if (res.code == 200) {
          this.refresh = true
          this.school = undefined
          this.staff = undefined
          this.type = undefined
          this.selectedProductList = []
          this.$router.push({path:"/product-stock"})

          this.$alert("", "提交成功", {
            confirmButtonText: "确定"
          });
        }
      });
    }
  },
  beforeRouteLeave(to,from,next){
        if (this.refresh){
          to.meta.refresh = 'a'
          this.refresh = undefined
        }
        if (this.$route.query.id == undefined){
            from.meta.keep = true
            from.meta.type = this.type
            from.meta.school = this.school
            from.meta.staff = this.staff
            from.meta.selectedProductList = this.selectedProductList
        }

        next()
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.keep){
                to.meta.keep = undefined
                next(v=>{
                  v.type = to.meta.type
                  v.school = to.meta.school
                  v.staff = to.meta.staff
                  v.selectedProductList = to.meta.selectedProductList
                  to.meta.type = undefined
                  to.meta.school = undefined
                  to.meta.staff = undefined
                  to.meta.selectedProductList = undefined
                })
            }
            else{
                next()
            }

        },

  created() {
    if ((this.info.school[0].headquarter == 1) || (this.info.school[0].headquarter == 2)){
      this.headquarter = 1
    }
    this.getSchoolList(-1);
    if (this.$route.query.id != undefined) {
      this.editShow = true;
      this.disabled = true;
    }
  }
};
</script>
